package httputil

import (
	"io/ioutil"
	"net/http"
	"strings"
	"net/url"
)

type Jar struct {
	cookies []*http.Cookie
}

func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
	jar.cookies = cookies
}
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
	return jar.cookies
}


func Get(url string,params map[string]string,successFn func(string),failFn func(error)) {
	s := "?";
	if strings.Index(url,"?")>0{
		s=""
	}
	//遍历map
	if(len(params)>0){
		url+=s
		for k, v := range params {
			url+="&"+k+"="+v
		}
	}

	resp, err := http.Get(url)
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	successFn(string(body))
}
func Post(url string,params map[string]string,successFn func(string),failFn func(error)) {
	s := "";

	//遍历map
	if(len(params)>0){
		i:=0
		for k, v := range params {
			if i==0{
				s+=k+"="+v
			}else{
				s+="&"+k+"="+v
			}
			i++
		}
	}

	resp, err := http.Post(url,"application/x-www-form-urlencoded",strings.NewReader(s))
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// handle error
		failFn(err)
		return
	}

	successFn(string(body))
}

func Request(requestUrl string,method string,headers map[string]string,params map[string]string) string {

	values := url.Values{}
	if(len(params)>0) {
		for k, v := range params {
			values.Set(k, v)
		}
	}
	data := ioutil.NopCloser(strings.NewReader(values.Encode())) //把form数据编下码
	client := &http.Client{}
	req, _ := http.NewRequest(method, requestUrl, data)
	if method=="POST"{
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") //这个一定要加，不加form的值post不过去，被坑了两小时
	}
	if(len(headers)>0) {
		for k, v := range headers {
			req.Header.Set(k, v)
		}
	}

	resp, err := client.Do(req) //发送

	if err != nil {
		// handle error
		println(err)
		panic(err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		// handle error
		println(err)
		panic(err)
	}

	return string(body)
}